<template>
  <div class="app-container">
    <div class="back-item" v-if="!open">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="商品名" prop="productName" >
          <el-input
              v-model="queryParams.productName"
              placeholder="请输入商品名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId" v-if="showSearch">
          <el-input
              v-model="queryParams.brandId"
              placeholder="请输入品牌"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="标签" prop="labelId" v-if="showSearch">
          <el-input
              v-model="queryParams.labelId"
              placeholder="请输入标签"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品品类" prop="firstCategoryId" >
          <el-cascader
            v-model="categoryIds.queryIds"
            :options="categoryTree"
            :props="{label:'categoryName',value:'categoryId'}"
            @change="handleQuerySort"
            placeholder="请选择品类信息"
            filterable
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId" >
          <el-input
              v-model="queryParams.supplierId"
              placeholder="请输入供应商"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发货地" prop="origin" v-if="showSearch">
          <el-input
              v-model="queryParams.origin"
              placeholder="请输入发货地"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="邮费类型" prop="postage" v-if="showSearch">
          <el-select v-model="queryParams.postage"  placeholder="请选择邮费类型">
            <el-option label="包邮" value="0" />
            <el-option label="自费" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="warning" icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button size="mini" @click="changSearch">{{showSearch?"常用条件":"所有条件"}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="back-item"  v-if="!open">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['mall:product:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="success"
              plain
              icon="Edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['mall:product:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="Delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['mall:product:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['mall:product:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="productList"
          @selection-change="handleSelectionChange"
          @row-dblclick="handleDetails"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="商品Id" align="center" prop="productId" v-if="columns[0].visible"/>
        <el-table-column label="商品名" align="center" prop="productName" v-if="columns[1].visible"/>
        <el-table-column label="商品首图" align="center" prop="firstImg" v-if="columns[2].visible">
          <template #default="scope">
            <el-image :src="scope.row.firstImg"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" prop="brandId" v-if="columns[3].visible"/>
        <el-table-column label="标签" align="center" prop="labelId" v-if="columns[4].visible"/>
        <el-table-column label="邮费模板" align="center" prop="templateId" v-if="columns[5].visible"/>
        <el-table-column label="一级品类" align="center" prop="firstCategoryId" v-if="columns[6].visible">
          <template #default="scope">
            {{`${categoryNames[scope.row.firstCategoryId]}
            /${categoryNames[scope.row.secondCategoryId]}
            /${categoryNames[scope.row.thirdCategoryId]}`}}
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="center" prop="supplierId" v-if="columns[9].visible"/>
        <el-table-column label="真实销量" align="center" prop="saleNum" v-if="columns[10].visible"/>
        <el-table-column label="虚拟销量" align="center" prop="virtualNum" v-if="columns[11].visible"/>
        <!--<el-table-column label="视频链接" align="center" prop="productVideo" v-if="columns[12].visible"/>-->
        <el-table-column label="库存" align="center" prop="totalNum" v-if="columns[13].visible"/>
        <el-table-column label="商品价格" align="center" prop="salePrice" v-if="columns[14].visible"/>
        <el-table-column label="划线价" align="center" prop="linePrice" v-if="columns[15].visible"/>
        <el-table-column label="发货地" align="center" prop="origin" v-if="columns[16].visible"/>
        <el-table-column label="邮费类型" align="center" prop="postage" v-if="columns[17].visible">
          <template #default="scope">
            {{scope.row.postage==0?"包邮":scope.row.postage==1?"自费":"-"}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" v-if="columns[18].visible">
          <template #default="scope">
            {{scope.row.status==0?"上架":scope.row.status==1?"下架":"-"}}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" v-if="columns[19].visible">
          <template #default="scope">
            {{scope.row.auditStatus==0?"审核中":scope.row.auditStatus==1?"通过":scope.row.auditStatus==2?"不通过":"-"}}
          </template>
        </el-table-column>
        <el-table-column label="发票" align="center" prop="invoiceStatus" v-if="columns[20].visible">
          <template #default="scope">
            {{scope.row.status==0?"可开":scope.row.status==1?"不可开":"-"}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width"
            v-if="columns[24].visible"
        >
          <template #default="scope">
            <el-button
                size="mini"
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['mall:product:edit']"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="Delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
                v-hasPermi="['mall:product:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
      <div class="line-magin"></div>
    </div>
    <edits v-if="open" :title="title" :id="id" @closedits="closEdits"></edits>

  </div>
</template>

<script setup name="Product">
  import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/mall/product";
  import { treeListCategory, } from "@/api/mall/category";

  const { proxy } = getCurrentInstance();
  import imgUpload from "@/components/upload/imgUpload";
  import edits from "./edits"
  // 遮罩层
  const loading = ref(true);
  // 导出遮罩层
  const exportLoading = ref(false);
  // 选中数组
  const ids = ref([]);
  // 主键Id
  const id = ref(null);
  // 非单个禁用
  const single = ref(true);
  // 非多个禁用
  const multiple = ref(true);
  // 切换搜索条件
  const showSearch = ref(false);
  // 总条数
  const total = ref(0);
  // 商品表格数据
  const productList = ref([]);
  //商品品类树
  const categoryTree = ref([]);
  const categoryNames = ref({});

  //商品规格编辑
  const standardArr = ref([])
  // 弹出层标题
  const title = ref("");
  // 弹出层
  const open = ref(false);
  const data = reactive({
    // 列信息
    columns: [
      {key: 0, label: `商品Id`, visible: true},
      {key: 1, label: `商品名`, visible: true},
      {key: 2, label: `商品首图`, visible: true},
      {key: 3, label: `品牌`, visible: true},
      {key: 4, label: `标签`, visible: true},
      {key: 5, label: `邮费模板`, visible: true},
      {key: 6, label: `一级品类`, visible: true},
      {key: 7, label: `二级品类`, visible: true},
      {key: 8, label: `三级品类`, visible: true},
      {key: 9, label: `供应商`, visible: true},
      {key: 10, label: `真实销量`, visible: true},
      {key: 11, label: `虚拟销量`, visible: true},
      {key: 12, label: `视频链接`, visible: true},
      {key: 13, label: `库存`, visible: true},
      {key: 14, label: `商品价格`, visible: true},
      {key: 15, label: `划线价`, visible: true},
      {key: 16, label: `发货地`, visible: true},
      {key: 17, label: `邮费类型 0:包邮，1：自费`, visible: true},
      {key: 18, label: `状态 0上架 1下架`, visible: true},
      {key: 19, label: `审核状态 0审核中 1通过 2不通过`, visible: true},
      {key: 20, label: `发票  0：可开，1：不可开`, visible: true},
      {key: 21, label: `创建时间`, visible: true},
      {key: 22, label: `创建者`, visible: true},
      {key: 23, label: `更新时间`, visible: true},
      {key: 24, label: `操作`, visible: true},
    ],
    // 查询参数
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      productName: null,
      firstImg: null,
      brandId: null,
      labelId: null,
      templateId: null,
      firstCategoryId: null,
      secondCategoryId: null,
      thirdCategoryId: null,
      supplierId: null,
      saleNum: null,
      virtualNum: null,
      productVideo: null,
      totalNum: null,
      salePrice: null,
      linePrice: null,
      origin: null,
      postage: null,
      status: null,
      auditStatus: null,
      invoiceStatus: null,
      details: null,
    },
    categoryIds: {
      queryIds: [],
    }
  });
  const { columns, queryParams, form, rules, categoryIds } = toRefs(data);

  /** 查询商品列表 */
  function getList() {
    loading.value = true;
    listProduct(queryParams.value).then(response => {
      productList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  //获取树形品类列表
  function getCategoryTree(){
    treeListCategory().then(response => {
      categoryTree.value = response.data
      setCategoryNames(categoryTree.value)
    })
  }
  //设置品类名map
  function setCategoryNames(categoryTree) {
    for (let item of categoryTree){
      categoryNames.value[item.categoryId] = item.categoryName
      if (item.children && item.children.length){
        setCategoryNames(item.children)
      }
    }
  }

  /** 品类选择-query */
  function handleQuerySort(values){
    if (values&&values.length == 3){
      queryParams.value.firstCategoryId = values[0];
      queryParams.value.secondCategoryId = values[1];
      queryParams.value.thirdCategoryId = values[2];
    }else {
      if(values){
        categoryIds.value.queryIds = [];
        proxy.$modal.msgWarning("请选择完整品类!")
      }
      queryParams.value.firstCategoryId = null;
      queryParams.value.secondCategoryId = null;
      queryParams.value.thirdCategoryId = null;

    }

  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }
  function closEdits(e) {
    console.log(e);
    open.value = false;
    id.value = null;
    if(e){
      getList()
    }
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }
  /** 切换按钮操作 */
  function changSearch() {
    showSearch.value = !showSearch.value;
  }
  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.productId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  /** 新增按钮操作 */
  function handleAdd() {
    id.value = null;
    open.value = true;
    title.value = "添加商品";
  }
  /** 修改按钮操作 */
  function handleUpdate(row) {
    id.value = row.productId || ids.value
    open.value = true;
    title.value = "修改商品";

  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const productIds = row.productId || ids.value;
    proxy.$modal.confirm('是否确认删除商品编号为\"' + productIds + '\"的数据项?').then(() => {

      return delProduct(productIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }
  /** 导出按钮操作 */
  function handleExport() {
    exportLoading.value = true;
    proxy.download("system/post/export", {
      ...queryParams.value
    }, `商品表_${new Date().getTime()}.xlsx`).then(response => {
      exportLoading.value = false;
    }).catch(error => {
      exportLoading.value = false;
    });
  }
  getCategoryTree()
  getList();
</script>
